package cn.com.haopy.yue.ai.admin.web;


import cn.com.haopy.yue.ai.admin.utils.AdminResponseCode;
import cn.com.haopy.yue.ai.admin.utils.Permission;
import cn.com.haopy.yue.ai.admin.utils.PermissionUtil;
import cn.com.haopy.yue.ai.core.component.SecurityComponent;
import cn.com.haopy.yue.ai.core.config.shiro.AdminUsernamePasswordToken;
import cn.com.haopy.yue.ai.core.system.SystemConfig;
import cn.com.haopy.yue.ai.core.utils.AESUtil;
import cn.com.haopy.yue.ai.core.utils.IpUtil;
import cn.com.haopy.yue.ai.core.utils.JacksonUtil;
import cn.com.haopy.yue.ai.core.utils.ResponseUtil;
import cn.com.haopy.yue.ai.db.entity.arisk.HOSAdmin;
import cn.com.haopy.yue.ai.db.service.hos.HOSAdminService;
import cn.com.haopy.yue.ai.db.service.hos.HOSPermissionService;
import cn.com.haopy.yue.ai.db.service.hos.HOSRoleService;
import com.google.code.kaptcha.Producer;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("/admin/auth")
@Validated
@Api(tags = "身份认证相关")
public class AdminAuthController {
    private final Log logger = LogFactory.getLog(AdminAuthController.class);

    @Autowired
    private HOSAdminService adminService;
    @Autowired
    private HOSRoleService roleService;
    @Autowired
    private HOSPermissionService permissionService;
    @Autowired
    private Producer kaptchaProducer;

    @Autowired
    private SecurityComponent securityComponent;

    @GetMapping("/kaptcha")
    @ApiOperation("验证码")
    public Object kaptcha(HttpServletRequest request) {
        String kaptcha = doKaptcha(request);
        if (kaptcha != null) {
            return ResponseUtil.ok(kaptcha);
        }
        return ResponseUtil.fail();
    }

    private String doKaptcha(HttpServletRequest request) {
        // 生成验证码
        String text = kaptchaProducer.createText();
        BufferedImage image = kaptchaProducer.createImage(text);
        HttpSession session = request.getSession();
        session.setAttribute("kaptcha", text);

        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ImageIO.write(image, "jpeg", outputStream);
            String base64 = Base64.getEncoder().encodeToString(outputStream.toByteArray());
            return "data:image/jpeg;base64," + base64.replaceAll("\r\n", "");
        } catch (IOException e) {
            return null;
        }
    }

    /*
     *  { username : value, password : value }
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Object login(@RequestBody String body, HttpServletRequest request) {
        String username = JacksonUtil.parseString(body, "username");
        String password = JacksonUtil.parseString(body, "password");
        String code = JacksonUtil.parseString(body, "code");

        return login(username, password, code, request);
    }

    @PostMapping("/loginByEncrypted")
    @ApiOperation("登录-加密")
    public Object loginByEncrypted(@RequestBody String body, HttpServletRequest request) {
        String cipher = JacksonUtil.parseString(body, "cipher");
        String key = SystemConfig.getSystemIntfcSecretAesKey();
        String decryptedBody;
        try {
            decryptedBody = AESUtil.decrypt(cipher, key);
        } catch (Exception e) {
            return ResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_KAPTCHA, "用户名、密码不正确", doKaptcha(request));
        }

        String username = JacksonUtil.parseString(decryptedBody, "username");
        String password = JacksonUtil.parseString(decryptedBody, "password");
        String code = JacksonUtil.parseString(decryptedBody, "code");

        return login(username, password, code, request);
    }


    private Object login(String username, String password, String code, HttpServletRequest request) {
        if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
            return ResponseUtil.badArgument();
        }
        if (!StringUtils.hasText(code)) {
            return ResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_KAPTCHA_REQUIRED, "验证码不能空", doKaptcha(request));
        }

        HttpSession session = request.getSession();
        String kaptcha = (String) session.getAttribute("kaptcha");
        if (StringUtils.isEmpty(code) ||
                StringUtils.isEmpty(kaptcha) ||
                code.compareToIgnoreCase(kaptcha) != 0) {
            return ResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_KAPTCHA, "验证码不正确", doKaptcha(request));
        }

        String ip = IpUtil.getIpAddr(request);
        try {
            securityComponent.checkLock(username, SecurityComponent.CLIENT_TYPE_ADMIN, ip);
        } catch (Exception ex) {
            return ResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT, ex.getMessage(), doKaptcha(request));
        }

        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.login(new AdminUsernamePasswordToken(username, password));
        } catch (UnknownAccountException uae) {
            Integer remain = securityComponent.loginFailed(username, SecurityComponent.CLIENT_TYPE_ADMIN, ip);
            return ResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT, "用户帐号或密码不正确，剩余" + remain + "次机会", doKaptcha(request));
        } catch (LockedAccountException lae) {
            Integer remain = securityComponent.loginFailed(username, SecurityComponent.CLIENT_TYPE_ADMIN, ip);
            return ResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT, "用户帐号不可用，剩余" + remain + "次机会", doKaptcha(request));
        } catch (AuthenticationException ae) {
            Integer remain = securityComponent.loginFailed(username, SecurityComponent.CLIENT_TYPE_ADMIN, ip);
            return ResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT, "认证失败，剩余" + remain + "次机会", doKaptcha(request));
        }

        securityComponent.removeLock(username, SecurityComponent.CLIENT_TYPE_ADMIN, ip);

        currentUser = SecurityUtils.getSubject();
        HOSAdmin admin = (HOSAdmin) currentUser.getPrincipal();
        admin.setLastLoginIp(ip);
        admin.setLastLoginTime(LocalDateTime.now());
        adminService.updateById(admin);


        // userInfo
        Map<String, Object> adminInfo = new HashMap<String, Object>();
        adminInfo.put("name", admin.getUsername());
        adminInfo.put("avatar", admin.getAvatar());

        Map<Object, Object> result = new HashMap<Object, Object>();
        result.put("token", currentUser.getSession().getId());
        result.put("adminInfo", adminInfo);

        result.put("passwordExpired", securityComponent.checkPasswordExpired(admin.getLastChangePasswordTime()));

        return ResponseUtil.ok(result);
    }

    /*
     *
     */
    @RequiresAuthentication
    @PostMapping("/logout")
    @ApiOperation("退出")
    public Object logout() {
        Subject currentUser = SecurityUtils.getSubject();

        currentUser.logout();
        return ResponseUtil.ok();
    }


    @RequiresAuthentication
    @GetMapping("/info")
    @ApiOperation("登录信息")
    public Object info() {
        Subject currentUser = SecurityUtils.getSubject();
        HOSAdmin admin = (HOSAdmin) currentUser.getPrincipal();

        Map<String, Object> data = new HashMap<>();
        data.put("name", admin.getUsername());
        data.put("avatar", admin.getAvatar());

        Integer[] roleIds = admin.getRoleIds();
        Set<String> roles = roleService.queryByIds(roleIds);
        Set<String> permissions = permissionService.queryByRoleIds(roleIds);
        data.put("roles", roles);
        // NOTE
        // 这里需要转换perms结构，因为对于前端而已API形式的权限更容易理解
        data.put("perms", toApi(permissions));
        return ResponseUtil.ok(data);
    }

    @Autowired
    private ApplicationContext context;
    private HashMap<String, String> systemPermissionsMap = null;

    private Collection<String> toApi(Set<String> permissions) {
        if (systemPermissionsMap == null) {
            systemPermissionsMap = new HashMap<>();
            final String basicPackage = "cn.com.haopy.yue.ai.admin";
            List<Permission> systemPermissions = PermissionUtil.listPermission(context, basicPackage);
            for (Permission permission : systemPermissions) {
                String perm = permission.getRequiresPermissions().value()[0];
                String api = permission.getApi();
                systemPermissionsMap.put(perm, api);
            }
        }

        Collection<String> apis = new HashSet<>();
        for (String perm : permissions) {
            String api = systemPermissionsMap.get(perm);
            apis.add(api);

            if (perm.equals("*")) {
                apis.clear();
                apis.add("*");
                return apis;
                //                return systemPermissionsMap.values();

            }
        }
        return apis;
    }

    @GetMapping("/401")
    public Object page401() {
        return ResponseUtil.unlogin();
    }

    @GetMapping("/index")
    public Object pageIndex() {
        return ResponseUtil.ok();
    }

    @GetMapping("/403")
    public Object page403() {
        return ResponseUtil.unauthz();
    }
}
